package com.wc.acwing.思维.农夫约翰最喜欢的操作;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2025/2/24 22:54
 * @description
 * https://www.acwing.com/problem/content/6134/
 */
public class Main {
    /**
     * 思路：
     * 操作 +1 与 -1 使得 (a[i] - x) % m == 0
     * =>   a[i] % m == x % m
     * 也就是所有的 a[i] 到达 x 距离之和的最小值, 但是 a[i] % m + m -> x, 也是有可能的
     * 是有序序列达到全部到达中间点保证了最小值, 也就是到达中间的位置
     * 可以形成一个链 使得短链的左边到达 x, 断链的右边达到 x
     * 讲解视频：https://www.acwing.com/video/5541/
     */
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 400010;
    static long[] a = new long[N], s = new long[N];
    static int n, m;

    public static void main(String[] args) {
        int T = sc.nextInt();
        while (T-- > 0) {
            n = sc.nextInt();
            m = sc.nextInt();
            for (int i = 1; i <= n; i++) {
                a[i] = sc.nextInt();
                a[i] %= m;
            }
            Arrays.sort(a, 1, n + 1);
            for (int i = 1; i <= n; i++) a[i + n] = a[i] + m;
            for (int i = 1; i <= 2 * n; i++) s[i] = s[i - 1] + a[i];
            long res = (long) 1e18;
            for (int l = 1; l <= n; l++) {
                int r = l + n - 1, p = (l + r) >> 1;
                long left =  (p - l + 1) * a[p] - (s[p] - s[l - 1]);
                long right = s[r] - s[p] - (r - p) * a[p];
                res = Math.min(res, left + right);
            }
            out.println(res);
        }
        out.flush();
    }
}
class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}

